// load libraries
var http = require("http"),
    ws = require("./node-websocket-server/lib/ws/server");

// ignore exception (to keep server working)
process.on('uncaughtException', function(err) {
    console.log(err);
});

// create HTTP SERVER instance
var httpServer = http.createServer(function(req, res) {
    res.writeHead(200);
    res.end('It works!!');
});

// create WebSocket SERVER instance based on HTTP SERVER
var server = ws.createServer({
    server: httpServer
});

// callback to lisening
server.addListener("listening", function(){
});

// per connection callback
server.addListener("connection", function(conn){
    // every received messages are broadcasted to all participants
    // exclude for sender.
    conn.addListener("message", function(message){
        if(message == "_ping")
            conn.send("_pong");
        else
            conn.broadcast(message);
    });
});

// callback to close conncetion.
server.addListener("close", function(conn){
    console.log("somebody disconnected");
});

// start server
//httpServer.listen(process.env.C9_PORT);
httpServer.listen(8090);

// console message. it indicates server is working:)
//console.log('server running...'+process.env.C9_PORT);
console.log('server running...'+8090);

